import enumJson from '@/common/enum/index.json'

// 关闭当前页跳转
export function toRedi(_page) {
    _page = _page.startsWith('pages/') ? _page : 'pages/' + _page
    uni.redirectTo({
        url: '/' + _page,
        animationType: 'zoom-fade-out',
        animationDuration: 300
    })
}

export function toTab(_page) {
    _page = _page.startsWith('pages/') ? _page : 'pages/' + _page
    uni.switchTab({
        url: '/' + _page
    })
}

export function toBack() {
    uni.navigateBack({
        delta: 1
    });
}

export function to(_page) {
    let tabs = enumJson.tabbar
    _page = _page.startsWith('pages/') ? _page : 'pages/' + _page
    if (tabs.includes(_page)) {
        uni.switchTab({
            url: '/' + _page,
        })
        return
    } else {
        uni.navigateTo({
            url: '/' + _page,
            animationType: 'zoom-fade-out',
            animationDuration: 300
        })
        return
    }
}


// 成功弹窗
export function sToast(title, duration) {
    uni.showToast({
        title,
        mask: true,
        duration: duration || 1500,
    })
}
// 弹窗
export function toast(title, duration) {
    uni.showToast({
        title,
        mask: true,
        icon: "none",
        duration: duration || 1500,
    })
}


// 2000年截至到今年的年月份
export function AsDate() {
    let this_year = new Date().getFullYear()
    let arr = [
        [],
        []
    ]
    for (let i = 2000; i <= this_year; i++) {
        let data = {
            value: i,
            label: i + '年'
        }
        arr[0].push(data)
    }

    for (let i = 1; i <= 12; i++) {
        let data = {
            value: i,
            label: i + '月'
        }
        arr[1].push(data)
    }

    return arr
}

// 返回00-24小时时间
export function backTime(step) {
    let date = new Date()
    date.setHours(0) // 时分秒设置从零点开始
    date.setSeconds(0)
    date.setUTCMinutes(0)

    console.log(date.getHours())
    console.log(date.getSeconds())
    console.log(new Date(date.getTime()))
    let arr = [
        [],
        []
    ]
    let timeArr = []
    let slotNum = 24 * 60 / step // 算出多少个间隔

    for (let f = 0; f < slotNum; f++) { //  stepM * f = 24H*60M
        // arr.push(new Date(Number(date.getTime()) + Number(step*60*1000*f)))   //  标准时间数组
        let time = new Date(Number(date.getTime()) + Number(step * 60 * 1000 * f)) // 获取：零点的时间 + 每次递增的时间
        let hour = '',
            sec = '';
        time.getHours() < 10 ? hour = '0' + time.getHours() : hour = time.getHours() // 获取小时
        time.getMinutes() < 10 ? sec = '0' + time.getMinutes() : sec = time.getMinutes() // 获取分钟
        timeArr.push(hour + ':' + sec)
    }

    timeArr = timeArr.map(item => {
        return {
            value: item,
            label: item
        }
    })
    let reverse = JSON.stringify(timeArr)
    arr[0] = timeArr
    arr[1] = JSON.parse(reverse).reverse()
    return arr
}

// 复制
export function setClipboardData(data) {
    return new Promise((success, fail) => {
        // #ifndef H5
        uni.setClipboardData({
                data,
                success,
                fail
            })
            // #endif

        // #ifdef H5
        const textarea = document.createElement('textarea')
        textarea.value = data
        textarea.readOnly = true
        document.body.appendChild(textarea)
        textarea.select()
        textarea.setSelectionRange(0, data.length)
        document.execCommand('copy')
        textarea.remove()
        success(data)
            // #endif
    })
}

// 拨打电话
export function callPhone(phone) {
    uni.makePhoneCall({
        phoneNumber: phone.toString(),
        success(res) {
            console.log(res, "成功拨打")
        },
        fail(err) {
            console.log(err, "失败拨打")
        }
    })
}


// 获取今日的日期
export function getNowDate(obj) {
    let date = {}
    if (obj instanceof Date) {
        date = obj
    } else {
        date = new Date();
    }
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate()
    month = month < 10 ? `0${month}` : month
    day = day < 10 ? `0${day}` : day
    let currentDate = {
        year,
        month,
        day
    };

    return currentDate
}

// 获取本周的日期
export function getWeekDate() {
    //按周日为一周的最后一天计算  
    let date = new Date();
    let this_day = date.getDay(); //今天是这周的第几天  
    let step_s = -this_day + 1; //上周日距离今天的天数（负数表示）  
    if (this_day == 0) {
        step_s = -7; // 如果今天是周日  
    }
    let step_m = 7 - this_day; // 周日距离今天的天数（负数表示）  
    let thisTime = date.getTime();
    let monday = new Date(thisTime + step_s * 24 * 3600 * 1000);
    let sunday = new Date(thisTime + step_m * 24 * 3600 * 1000);
    //默认统计一周的时间  
    let startDate = getNowDate(monday); //本周一的日期 （起始日期）  
    let endDate = getNowDate(sunday); //本周日的日期 （结束日期）  
    return {
        startDate,
        endDate
    }
}
// 拼接时间
export function splitDate(obj) {
    return obj.year + '-' + obj.month + '-' + obj.day
}

// 将对象数组某个字段分离出来并返回新的数组
export function pointsField(arr, field) {
    let newArr = []
    arr.map((item, index) => {
        if (item instanceof Object) {
            let c = item[field]
            newArr.push(c)
        } else {
            newArr.push(item)
        }
    })
    return newArr
}



// 截取后缀名
export function getSuffix(value) {
    let newValue
    if (value && typeof value != 'string') {
        value = value.toString()
        console.error('请传入正确的格式啊!')
        return
    }

    if (value && value.lastIndexOf('.') != -1) {
        console.log(value)
        newValue = value.slice(value.lastIndexOf('.'))
    } else {
        console.error('请传入正确的格式!');
        return
    }
    return newValue
}

// 上传文件
export function uploadFile(url, filePath, formData = {}) {
    return new Promise((resolve, reject) => {
        const uploadTask = uni.uploadFile({
            url,
            filePath,
            name: 'file',
            formData,
            success: (res) => {
                resolve(res)
            },
            fail: (err) => {
                reject(err)
            }
        })

        uploadTask.onProgressUpdate(res => {
            const SIZE = 20 * 1024 * 1024
            if (res.totalBytesSent > SIZE) {
                uni.showToast({
                    title: `请上传20M以内的多媒体资源!`,
                    icon: "none",
                    mask: true
                })
                uploadTask.abort()
            }
        })
    })

}

// 获取当前页面
export function getCurPage(query) {
    let routers = getCurrentPages()
    let cur = routers[routers.length - 1].route
    return cur + `?${query}`
}


// https://uniapp.dcloud.io/api/other/authorize?id=scope-%e5%88%97%e8%a1%a8 查看scope键值
// #ifndef H5 || APP-PLUS || MP-ALIPAY
// 打开授权
export function openAuthorize(scopeKey){
    
    uni.getSetting({
        success:auth=>{
            let flag = Object.keys(auth.authSetting).some(key=> auth.authSetting[`scope.${scopeKey}`] == false || auth.authSetting[`scope.${scopeKey}`] == undefined)
            console.log(flag,"是否开启授权",auth);
            if(flag){
                console.log("没有开启相关权限");
                uni.authorize({
                    scope:`scope.${scopeKey}`,
                    success: (r) => {
                        console.log(r,"弹起授权");
                    },
                    fail: (e) => {
                        console.log(e,"拒绝授权");
                        uni.showModal({
                            title:"提示",
                            content:"授权失败,请点击确定重新授权!",
                            success:result=>{
                                if(result.confirm){
                                    uni.openSetting({
                                        success:res=>{
                                            console.log(res,"开启权限");
                                        }
                                    })
                                }
                            }
                        })
                    }
                })
            
            }
        }
    })
}
// #endif